package cn.edu.sig.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.stereotype.Repository;

import cn.edu.sig.bean.CurrentPage;
import cn.edu.sig.bean.History;
import cn.edu.sig.bean.Style;
import cn.edu.sig.bean.User;
import cn.edu.sig.dao.HistoryDao;
import cn.edu.sig.util.PaginationHelper;

@Repository("historyDao")
public class HistoryDaoImpl extends TemplateSupport implements HistoryDao {

	public void add(History history) {
		String sql = this.sqlSource.getSql("history.add");

		Object[] param = new Object[] { history.getContent(),
				history.getCreateTime(), history.getUser().getCode() };

		this.getJdbcTemplate().update(sql, param);

	}

	public void delete(Integer historyId) {

		String sql = this.sqlSource.getSql("image.delete");

		this.getJdbcTemplate().update(sql, historyId);

	}

	public void edit(History history) {

		String sql = this.sqlSource.getSql("image.add");

		Object[] param = new Object[] { history.getContent() };

		this.getJdbcTemplate().update(sql, param);

	}

	public List<History> findAll() {
		String sql = this.sqlSource.getSql("image.list");
		RowMapper<History> mapper = new RowMapper<History>() {
			public History mapRow(ResultSet rs, int rowNum) throws SQLException {

				History history = new History();

				history.setHistoryId(rs.getInt("historyId"));
				history.setContent(rs.getString("content"));
				history.setCreateTime(rs.getDate("createTime"));

				return history;
			}
		};

		return this.getJdbcTemplate().query(sql, mapper);
	}

	public CurrentPage<History> findAllByUser(User user, int pageNo, int pageSize) {
		PaginationHelper<History> ph = new PaginationHelper<History>();

		String sqlCountRows = "select count(*) from history where code = ?";
		String sqlFetchRows = "select * from history where code = ? limit ? ,?";

		return ph.fetchPage(getJdbcTemplate(), sqlCountRows, sqlFetchRows, user
				.getCode(), pageNo, pageSize,
				new ParameterizedRowMapper<History>() {
					public History mapRow(ResultSet rs, int i)
							throws SQLException {

						History history = new History();

						history.setHistoryId(rs.getInt("historyId"));
						history.setContent(rs.getString("content"));
						history.setCreateTime(rs.getDate("createTime"));

						return history;
					}
				});

	}

	public History findById(String id) {
		return null;
	}

	public History findByName(String name) {
		return null;
	}

}
